# +----------------------------------------------------------------------
# | ChatWork智能聊天办公系统
# +----------------------------------------------------------------------
# | 软件声明: 本系统并非自由软件,未经授权任何形式的商业使用均属非法。
# | 版权保护: 任何企业和个人不允许对程序代码以任何形式任何目的复制/分发。
# | 授权要求: 如有商业使用需求,请务必先与版权所有者取得联系并获得正式授权。
# +----------------------------------------------------------------------
# | Author: ChatWork Team <2474369941@qq.com>
# +----------------------------------------------------------------------
import json
import time
from tortoise.expressions import Q
from hypertext import PagingResult
from common.utils.urls import UrlUtil
from common.models.users import UserModel
from common.models.docs import DocsFilesModel
from common.models.docs import DocsRecordsModel
from common.postgres.public import PgDocumentsModel
from apps.admin.schemas.apply.docs import record_schema as schema


class DocsRecordService:

    @classmethod
    async def lists(cls, params: schema.DocsRecordSearchIn) -> PagingResult[schema.DocsRecordListVo]:
        """
        记录列表。

        Args:
            params (schema.DocsRecordSearchIn): 查询参数。

        Returns:
            PagingResult[schema.DocsRecordListVo]: 分页列表Vo。

        Author:
            zero
        """
        # 查询条件
        where = DocsRecordsModel.build_search({
            "datetime": ["start_time|end_time@create_time"]
        }, params.__dict__)

        if params.filename and not params.file_id:
            condition = [Q(sn=params.filename), Q(is_delete=0)]
            files = await DocsFilesModel.filter(*condition).limit(500).values(str("id"))
            file_ids = [int(item["id"]) for item in files] or [0]
            where.append(Q(file_id__in=file_ids))

        if params.user:
            condition = [Q(sn=params.user), Q(is_delete=0)]
            users = await UserModel.filter(*condition).limit(200).values(str("id"))
            ids = [item["id"] for item in users] or [0]
            where.append(Q(user_id__in=ids))

        if params.file_id:
            where.append(Q(file_id=params.file_id))

        # 查询数据
        _model = DocsRecordsModel.filter(*where).order_by("-id")
        _pager = await DocsRecordsModel.paginate(
            model=_model,
            page_no=params.page_no,
            page_size=params.page_size
        )
        print("K歌科二科三")
        # 查询用户
        user_ids = [item["user_id"] for item in _pager.lists]
        users = await UserModel.queryUserDictsById(user_ids)

        # 查询文件
        file_dict = {}
        file_ids = [item["file_id"] for item in _pager.lists]
        if file_ids:
            file_list = await DocsFilesModel.filter(id__in=file_ids).all().values("id", "name")
            file_dict = {item["id"]: item["name"] for item in file_list}

        # 处理数据
        _lists = []
        for item in _pager.lists:
            user = users.get(item["user_id"]) or {}
            quotes = json.loads(item["quotes"] or "[]")
            flows_usage = json.loads(item["flows_usage"] or "[]")
            _lists.append(schema.DocsRecordListVo(
                id=item["id"],
                file_id=item["file_id"],
                code=item["code"],
                scene=item["scene"],
                filename=file_dict.get(item["file_id"], ""),
                question=item["question"],
                answer=item["answer"],
                use_points=item["use_points"],
                use_tokens=item["use_tokens"],
                is_clear=item["is_clear"],
                ip=item["ip"],
                task_time=item["task_time"],
                create_time=item["create_time"],
                quotes=quotes,
                usages=flows_usage,
                user={
                    "sn": user.get("sn", "").strip(),
                    "nickname": user.get("nickname", ""),
                    "mobile": user.get("mobile", ""),
                    "avatar": await UrlUtil.to_absolute_url(user.get("avatar", ""))
                }
            ))

        _pager.lists = _lists
        return _pager

    @classmethod
    async def delete(cls, id_: int):
        """
        记录删除。

        Args:
            id_ (int): 记录ID。

        Author:
            zero
        """
        await DocsRecordsModel.filter(id=id_).filter(is_delete=0).get()
        await DocsRecordsModel.filter(id=id_).update(
            is_delete=1,
            delete_time=int(time.time())
        )
        await PgDocumentsModel.filter(file_id=id_).delete()
